const { User, Transaction, StoredWine } = require('../models');
const { sequelize } = require('../config/database');
const { Op } = require('sequelize');

// 获取总览统计
exports.getOverview = async (req, res, next) => {
  try {
    // 用户总数
    const totalUsers = await User.count({ where: { role: 'customer' } });

    // 寄存酒总数（在库）
    const totalStoredWines = await StoredWine.count({ where: { status: 'stored' } });

    // 今日交易数
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayTransactions = await Transaction.count({
      where: {
        createdAt: { [Op.gte]: today }
      }
    });

    // 今日营业额（充值总额）
    const todayRecharge = await Transaction.sum('amount', {
      where: {
        type: 'recharge',
        createdAt: { [Op.gte]: today }
      }
    }) || 0;

    // 今日消费额
    const todayConsume = await Transaction.sum('amount', {
      where: {
        type: 'consume',
        createdAt: { [Op.gte]: today }
      }
    }) || 0;

    // 总余额
    const totalBalance = await User.sum('balance', { where: { role: 'customer' } }) || 0;

    res.json({
      success: true,
      data: {
        totalUsers,
        totalStoredWines,
        todayTransactions,
        todayRecharge: parseFloat(todayRecharge),
        todayConsume: parseFloat(todayConsume),
        totalBalance: parseFloat(totalBalance)
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取用户消费排行
exports.getUserRanking = async (req, res, next) => {
  try {
    const { limit = 10, startDate, endDate } = req.query;
    
    const where = { type: 'consume' };
    if (startDate && endDate) {
      where.createdAt = {
        [Op.between]: [new Date(startDate), new Date(endDate)]
      };
    }

    const ranking = await Transaction.findAll({
      attributes: [
        'userId',
        [sequelize.fn('SUM', sequelize.col('amount')), 'totalConsume'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'transactionCount']
      ],
      where,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'name', 'phone']
        }
      ],
      group: ['userId', 'user.id'],
      order: [[sequelize.fn('SUM', sequelize.col('amount')), 'DESC']],
      limit: parseInt(limit),
      raw: false
    });

    const formattedRanking = ranking.map((item, index) => ({
      rank: index + 1,
      userId: item.userId,
      userName: item.user?.name,
      phone: item.user?.phone,
      totalConsume: parseFloat(item.dataValues.totalConsume),
      transactionCount: parseInt(item.dataValues.transactionCount)
    }));

    res.json({
      success: true,
      data: formattedRanking
    });
  } catch (error) {
    next(error);
  }
};

// 获取寄存酒统计
exports.getWineStats = async (req, res, next) => {
  try {
    const { startDate, endDate } = req.query;
    
    const where = {};
    if (startDate && endDate) {
      where.storageDate = {
        [Op.between]: [new Date(startDate), new Date(endDate)]
      };
    }

    // 按状态统计
    const statusStats = await StoredWine.findAll({
      attributes: [
        'status',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count'],
        [sequelize.fn('SUM', sequelize.col('quantity')), 'totalQuantity']
      ],
      where,
      group: ['status'],
      raw: true
    });

    // 按酒类型统计
    const typeStats = await StoredWine.findAll({
      attributes: [
        'wineType',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count'],
        [sequelize.fn('SUM', sequelize.col('quantity')), 'totalQuantity']
      ],
      where,
      group: ['wineType'],
      order: [[sequelize.fn('COUNT', sequelize.col('id')), 'DESC']],
      limit: 10,
      raw: true
    });

    res.json({
      success: true,
      data: {
        byStatus: statusStats.map(s => ({
          status: s.status,
          count: parseInt(s.count),
          totalQuantity: parseFloat(s.totalQuantity)
        })),
        byType: typeStats.map(t => ({
          wineType: t.wineType,
          count: parseInt(t.count),
          totalQuantity: parseFloat(t.totalQuantity)
        }))
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取每日统计
exports.getDailyStats = async (req, res, next) => {
  try {
    const { startDate, endDate } = req.query;

    if (!startDate || !endDate) {
      return res.status(400).json({
        success: false,
        message: '请提供开始日期和结束日期'
      });
    }

    // 按日期分组统计交易
    const stats = await Transaction.findAll({
      attributes: [
        [sequelize.fn('DATE', sequelize.col('created_at')), 'date'],
        'type',
        [sequelize.fn('SUM', sequelize.col('amount')), 'total'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: {
        createdAt: {
          [Op.between]: [new Date(startDate), new Date(endDate)]
        }
      },
      group: [sequelize.fn('DATE', sequelize.col('created_at')), 'type'],
      order: [[sequelize.fn('DATE', sequelize.col('created_at')), 'ASC']],
      raw: true
    });

    // 格式化数据
    const formattedStats = {};
    stats.forEach(stat => {
      if (!formattedStats[stat.date]) {
        formattedStats[stat.date] = {
          date: stat.date,
          recharge: 0,
          consume: 0,
          rechargeCount: 0,
          consumeCount: 0
        };
      }
      
      if (stat.type === 'recharge') {
        formattedStats[stat.date].recharge = parseFloat(stat.total);
        formattedStats[stat.date].rechargeCount = parseInt(stat.count);
      } else if (stat.type === 'consume') {
        formattedStats[stat.date].consume = parseFloat(stat.total);
        formattedStats[stat.date].consumeCount = parseInt(stat.count);
      }
    });

    res.json({
      success: true,
      data: Object.values(formattedStats)
    });
  } catch (error) {
    next(error);
  }
};
